﻿/*
=========================================================
功能：      编辑页面必填项及输入类型验证
修改人：    王志海，于维海
修改时间：  2009-7-3
=========================================================
*/
//常量
var MaxLength = "maxLength";
var isShowTip = false; //是否已经显示了Tip
var isShowCustomTip = true; //是否显示自定义验证的Tip
var msgValue = "";
var retValueKind = false;
var RegexMark = "##";
var isIE = false;
var focusCtrl = null;
//判断浏览器
if ((navigator.userAgent.indexOf('MSIE') >= 0) && (navigator.userAgent.indexOf('Opera') < 0)) {
    isIE = true;
}

//动态添加CSS文件的引用
function add_css(str_css) {
    var fileref = document.createElement("link");
    fileref.setAttribute("rel", "stylesheet");
    fileref.setAttribute("type", "text/css");
    fileref.setAttribute("href", str_css);
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
}
/*
=========================================================
用于对当前页面控件输入值的验证
=========================================================
*/
function CheckPage() {
    //debugger;
    var js = document.scripts;
    var jsPath;
    for (var i = 0; i < js.length; i++) {
        if (js[i].src.indexOf("FormValidate.js") > -1) {
            jsPath = js[i].src.substring(0, js[i].src.lastIndexOf("/") + 1);
        }
    }
    //添加页面验证所用的CSS
    add_css(jsPath + "ValidateStyle.css");

    fctrl = null; //聚焦控件 默认置空
    isShowTip = false;
    retValueKind = true;
    var ctrls = document.getElementsByTagName('form')[0]; //ctrls是数组类型,数组大小只计算form类型(button,text,textarea,checkbox,select等)
    CreateDiv(); //ErrorDiv
    //kb  begin
    var idNum = 0;
    var validatespan = document.getElementById('validateNumSpan');
    if (validatespan == null || typeof (validatespan) == "undefined") {
        validatespan = document.createElement('span');
        validatespan.id = 'validateNumSpan';
        validatespan.style.display = "none";
        validatespan.html = "0";
        document.appendChild(validatespan);
    }
    else {
        idNum = validatespan.html;
    }
    for (var x = 0; x < ctrls.length; x++) {
        var ctrl = ctrls[x];
        if (ctrl.id == "") {
            $(ctrl).attr('id', "validate_" + idNum);
            idNum = parseInt(idNum) + 1;
        }
    }
    validatespan.html = idNum;

    for (var m = 0; m < ctrls.length; m++) {
        var __ctrl = ctrls[m];

        var ctrlId = __ctrl.id;
        if (ctrlId)
            AddBorder(ctrlId);

    }  //kb end
    for (var n = 0; n < ctrls.length && ctrls[n].id; n++) {
        var kind = true;
        var __ctrl = ctrls[n];
        if (__ctrl.tagName.toLowerCase() == "input") {
            kind = ValidateTextBox(__ctrl); //kind标示验证是否通过false表示未通过，true表示通过
        }
        else if (__ctrl.tagName.toLowerCase() == "textarea") {
            kind = ValidataTextArea(__ctrl)
        }
        else if
          (__ctrl.tagName.toLowerCase() == "select") {
            kind = ValidataDropList(__ctrl);
        }
        if (kind == false) {
            retValueKind = false; //retValueKind（即returnValueKind）标示验证是否通过,true表示通过，false表示未通过
            if (focusCtrl == null) {
                focusCtrl = __ctrl;
            }
        }
        ForEachCtrol(ctrls[n]);
    }
    //判断自定义判断方法是否存在
    if (typeof (CustomValid) == "function") {
        isShowCustomTip = true;
        if (CustomValid() == false) {
            retValueKind = false; //retValueKind（即returnValueKind）标示验证是否通过,true表示通过，false表示未通过
        }
    }

    //保存时为第一个验证不通过的控件聚焦
    if (!retValueKind && focusCtrl) {

        window.focus();
        try {
            focusCtrl.focus();
        } catch (e) {
        }
        focusCtrl = null;
    }

    return retValueKind;
}

function ForEachCtrol(ctrls) {
    if (ctrls.length <= 0) return;
    else {
        for (var n = 0; n < ctrls.length; n++) {
            var kind = true;
            var __ctrl = ctrls[n];
            if (__ctrl.tagName.toLowerCase() == "input") {
                kind = ValidateTextBox(__ctrl);
            }
            else if (__ctrl.tagName.toLowerCase() == "textarea") {
                kind = ValidataTextArea(__ctrl)
            }
            else if (__ctrl.tagName.toLowerCase() == "select") {
                kind = ValidataDropList(__ctrl);
            }
            if (kind == false) {
                retValueKind = false; //retValueKind是全局变量
            }

            ForEachCtrol(ctrls[n]);
        }
    }
}

/*
===================================================
验证TEXTBOX
===================================================
*/
function ValidateTextBox(ctrl) {
    var returnValues = true;
    var kind = true;
    var ctrlId = ctrl.id;
    if (ctrl.type == "text" || ctrl.type == "password") {
        if (ctrl.disabled == true) {//disabled表示失效的文本框(域)  ???????????????
            return true;
        }
        v = StrTrim(ctrl.value);
        if (v == "") {
            ctrl.value = "";
        }
        kind = Validata(ctrl, v); //kind标示验证是否通过
        if (kind == false) {
            var FieldType = "";
            if (ctrl.attributes["fieldtype"] != null)//文本长度
            {
                FieldType = ctrl.attributes["fieldtype"].value.toLowerCase();
            }
            if (ctrl.attributes["FieldType"] != null)//文本长度
            {
                FieldType = ctrl.attributes["FieldType"].value.toLowerCase();
            }
            if (FieldType == "datetime") {
                ctrl.onchange = function () {
                    _onblur(ctrl);
                }
            }
            ctrl.onfocus = function () {
                _onfocus(ctrl);
            }
            ctrl.onblur = function () {
                _onblur(ctrl);
            }
            ShowElementBorder(ctrlId);
            //ctrl.className = "input-error";
            returnValues = false;
        }
        else {
            HideElementBorder(ctrlId);
        }
    }
    return returnValues; //返回验证是否通过，True标示通过，False标示未通过
}

/*
===================================================
验证大文本框的长度
===================================================
*/
function ValidataTextArea(ctrl) {
    var returnValues = true;
    var txtlen = 0;
    var kind = true;
    if (ctrl.attributes["textlength"] != null)//文本长度
    {
        txtlen = ctrl.attributes["textlength"].value;
    }
    else if (ctrl.attributes["TextLength"] != null)//文本长度
    {
        txtlen = ctrl.attributes["TextLength"].value;
    }
    var Msg = "";

    if (ctrl.attributes["msg"] != null)//该文本代表的信息，这些属性是公司框架自定义的
    {
        Msg = ctrl.attributes["msg"].value;
    }
    else if (ctrl.attributes["Msg"] != null)//该文本代表的信息，这些属性是公司框架自定义的
    {
        Msg = ctrl.attributes["Msg"].value;
    }

    var v = StrTrim(ctrl.value);
    var ctrlId = ctrl.id;
    kind = Validata(ctrl, v); //kind标示验证是否通过
    if (kind == false) {
        ctrl.onfocus = function () {
            _onfocus(ctrl);
        }
        ctrl.onblur = function () {
            _onblur(ctrl);
        }
        ShowElementBorder(ctrlId);
        returnValues = false;
    }
    else {
        HideElementBorder(ctrlId);
    }
    return returnValues;
}

/*
===================================================
验证下拉框是否为必填
===================================================
*/
function ValidataDropList(ctrl) {
    returnValues = true;
    var ctrlId = ctrl.id;
    var v = "";
    v = StrTrim(ctrl.value);
    kind = Validata(ctrl, v);
    if (kind == false) {
        if (ctrl.selectedIndex != -1)
            ctrl.options[ctrl.selectedIndex].style.bgcolor = "#5199EA";

        ctrl.onfocus = function () {
            _onfocus(ctrl);
        }
        ctrl.onblur = function () {
            _onblur(ctrl);
        }

        var Msg = "";

        if (ctrl.attributes["Msg"] != null)//该文本代表的信息，这些属性是公司框架自定义的
        {
            Msg = ctrl.attributes["Msg"].value;
        }
        if (ctrl.attributes["msg"] != null)//该文本代表的信息，这些属性是公司框架自定义的
        {
            Msg = ctrl.attributes["msg"].value;
        }

        if (document.getElementById("ErrorDiv").style.visibility != "visible" || !isShowTip) {
            ValidatorUpdateDisplay(document.getElementById("ErrorDiv"), ctrl, Msg + "必选其中一项！");
            isShowTip = true;
        }

        returnValues = false;
        ShowElementBorder(ctrlId);
        //ctrl.className = "editTextarea";
    }
    else {
        HideElementBorder(ctrlId);
    }
    return returnValues;
}
function _onfocus(ctrl) {
    isShowTip = false;
    if (ctrl.tagName.toLowerCase() == "input") {
        kind = ValidateTextBox(ctrl);
    }
    else if (ctrl.tagName.toLowerCase() == "textarea") {
        kind = ValidataTextArea(ctrl)
    }
    else if (ctrl.tagName.toLowerCase() == "select") {
        kind = ValidataDropList(ctrl);
    }
}
function _onblur(ctrl) {
    isShowTip = false;
    if (ctrl.tagName.toLowerCase() == "input") {
        kind = ValidateTextBox(ctrl);
    }
    else if (ctrl.tagName.toLowerCase() == "textarea") {
        kind = ValidataTextArea(ctrl)
    }
    else if (ctrl.tagName.toLowerCase() == "select") {
        kind = ValidataDropList(ctrl);
    }
    if (kind) {
        HideWinErrMsgTips("ErrorDiv");
    }
}

/*
===================================================
创建DIV
*/
function CreateDiv() {
    var obj = document.getElementById("ErrorDiv");
    if (obj == null || typeof (obj) == "undefined") {
        var newNode = document.createElement("div");
        newNode.setAttribute("id", "ErrorDiv"); //设置属性
        //        newNode.innerHTML = "No.o";//<div >No.o</div>
        document.getElementsByTagName("form")[0].appendChild(newNode); //添加子节点<form><div><div></form>
    }
}

/*
===================================================================
验证输入的值
===================================================================
*/
function Validata(ctrl, val) {
    var returnValues = true;
    //验证信息
    var Msg = "";

    if (ctrl.attributes["msg"] != null)//该文本代表的信息，这些属性是公司框架自定义的
    {
        Msg = ctrl.attributes["msg"].value;
    }
    if (ctrl.attributes["Msg"] != null) {
        Msg = ctrl.attributes["Msg"].value;
    }
    ctrl.ErrorMessage = "";
    //判断是否可以为空
    var isNull = "true";
    if (ctrl.attributes["isnull"] != null) {
        isNull = ctrl.attributes["isnull"].value.toLowerCase();
    }
    else if (ctrl.attributes["IsNull"] != null) {
        isNull = ctrl.attributes["IsNull"].value.toLowerCase();
    }
    if (isNull == "false" && val == "") {
        ctrl.onfocus = "ctrlonfocus(ctrl);"
        ctrl.onblue = "ctrlonblur(ctrl);"

        if (document.getElementById("ErrorDiv").style.visibility != "visible" || !isShowTip) {
            HideWinErrMsgTips("ErrorDiv");
            ValidatorUpdateDisplay(document.getElementById("ErrorDiv"), ctrl, Msg + "不能为空！");
            isShowTip = true;
        }
        ctrl.ErrorMessage = Msg + "不能为空！";
        returnValues = false;
    }

    if (val != "") {
        if (!CheckText(ctrl)) {
            returnValues = false;
        }
    }
    return returnValues;
}
/*
==================================================
-------------验证数据精度-------------------
==================================================
*/
function CheckDataPrecision(ctrl, Msg) {
    var returnValues = true;
    return returnValues;
}
/*
==================================================
-------------对输入的值进行验证-------------------
==================================================
*/
function CheckText(ctrl) {
    var returnValue = true;
    ctrl.onfocus = "ctrlonfocus(ctrl);"
    ctrl.onblue = "ctrlonblur(ctrl);"
    var msgType;
    var flag = true; //标识验证是否通过
    var Msg = "";
    if (ctrl.attributes["msg"] != null)//该文本代表的信息，这些属性是公司框架自定义的
    {
        Msg = ctrl.attributes["msg"].value;
    }
    else if (ctrl.attributes["Msg"] != null) {
        Msg = ctrl.attributes["Msg"].value;
    }
    //*********************校验字段类型*********************************//
    var type = "string";

    if (ctrl.attributes["fieldtype"] != null) {
        type = ctrl.attributes["fieldtype"].value.toLowerCase();
    }
    else if (ctrl.attributes["FieldType"] != null) {
        type = ctrl.attributes["FieldType"].value.toLowerCase();
    }
    var val = StrTrim(ctrl.value);
    switch (type.toLowerCase()) {
        case "int":
            //debugger;
            //验证数据类型
            if (isNaN(val)) {
                msgType = "应输入数字!";
                flag = false;
            }
            else if (!valNumber(val, type.toLowerCase())) {
                msgType = "输入的数值超出范围!";
                flag = false;
            }
            else if (val < 0) {
                msgType = "输入的数值需大于等于0!";
                false = false;
            }
            break;
        case "smallint":
        case "tinyint":
        case "bigint":
            //验证数据类型
            if (isNaN(val)) {
                msgType = "应输入数字!";
                flag = false;
            }
            else if (!valNumber(val, type.toLowerCase())) {
                msgType = "输入的数值超出范围!";
                flag = false;
            }
            break;
        case "varchar":
            if (!VarcharValidLength(ctrl)) {
                msgType = "输入内容过多!";
                flag = false;
            }
            break;
        case "nvarchar":
            if (!NvarcharValidLength(ctrl)) {
                msgType = "输入内容过多!";
                flag = false;
            }
            break;
        case "string":
            if (!VarcharValidLength(ctrl)) {
                msgType = "输入内容过多!";
                flag = false;
            }
            break;
        case "decimal":
            //验证数据类型
            if (isNaN(val)) {
                msgType = "应输入数字!";
                flag = false;
            }
            else if (!isDecimal(ctrl)) {
                if (ctrl.attributes["precision"] != null) {
                    //获取设置的精度控制
                    precision = ctrl.attributes["precision"].value;
                }
                //拆分整数位和小数位
                var pre = precision.split(",");
                msgType = "应输入整数位最多" + (parseInt(pre[0], 10) - parseInt(pre[1], 10)) + "位,小数位最多" + parseInt(pre[1], 10) + "位的数值!";
                flag = false;
            }
            break;

    }
    //验证自定义正则表达式
    if (flag) {
        if (!CheckRegex(ctrl)) {
            var regexMsg = "";    //错误提示语
            if (ctrl.attributes["regex"] != null && regexMsg.indexOf(RegexMark) > 0) {
                regexMsg = ctrl.attributes["regex"].value.split(RegexMark)[1];
            }
            //msgType = "格式不正确!" + regexMsg;
            msgType = regexMsg;
            flag = false;
        }
    }
    if (!flag) {
        if (document.getElementById("ErrorDiv").style.visibility != "visible" || !isShowTip) {
            HideWinErrMsgTips("ErrorDiv");
            ValidatorUpdateDisplay(document.getElementById("ErrorDiv"), ctrl, Msg + msgType + msgValue);
            isShowTip = true;
        }
        returnValue = false;
    }
    return returnValue;
}

/*
======================================================
去除字符串左边及右边的空格
======================================================
*/
function StrTrim(str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}


/*
====================================================================================
检测字符串是否有非法字符
====================================================================================
*/
function CheckOtherChars(str) {
    msgValue = "";
    var chars = "!#%'/;'\"$^*|";
    var i;
    for (i = 0; i < str.length; i++) {
        if (chars.indexOf(str.charAt(i)) > -1) {
            msgValue = "不能含有‘!#%'/;'\"$^*|’非法字符！";
            return false;
        }

    }
    return true;

}

/*
================================================
清除查询条件
================================================
*/
function ClearCondition(ctrls) {
    var aryCtr = ctrls.split(",");

    for (var j = 0; j < aryCtr.length; j++) {
        var obj = eval("document.all." + aryCtr[j]);

        var Elements = obj.getElementsByTagName("*");
        for (var i in Elements) {
            var ctrl;
            try { ctrl = Elements[i]; }
            catch (e) {
                continue;
            }
            var ctrlType;
            try { ctrlType = ctrl.type.toLowerCase(); }
            catch (e) {
                ctrlType = "";
            }
            //alert(tag);
            if (ctrlType == "checkbox") {
                ctrl.checked = false;
            }
            if (ctrlType == "text" && ctrl.style.visibility != "hidden") {
                ctrl.value = "";
            }
            if (ctrlType == "select-one") {
                ctrl.selectedIndex = 0;
            }
            var ctrlTag;
            try { ctrlTag = ctrl.tagName.toLowerCase(); }
            catch (e) {
                ctrlTag = "";
            }
            //alert(ctrlType);
        }
    }
    var objRadio = document.getElementsByTagName("input");
    for (var i = 0; i < objRadio.length; i++) {

        if (objRadio(i).type == "radio") {
            var radioGroup = objRadio(i).name
            var radioButton = eval("document.all." + radioGroup + "")
            radioButton[1].checked = true;
            continue;
        }
    }
}

//////////////////////////////////////////////////////////////////////////Tip
var __Win__IsAutoClose = true;
var __Win__IsFilterClose = true;
var __Win__CloseWaitTime = 5500;
if (typeof (__Win__IsAutoClose) == "undefined" || typeof (__Win__IsFilterClose) == "undefined" || typeof (__Win__CloseWaitTime) == "undefined") {
    alert("初始化Js失败，请确定正确使用了气泡提示验证控件！")
}
var __Win__BlockFlag = false;


//关闭气泡提示
function HideWinErrMsgTips(elementid) {
    var ua = navigator.userAgent.toLowerCase();
    var isOpera = (ua.indexOf('opera') != -1);
    var isIE = (ua.indexOf('msie') != -1 && !isOpera);
    var objWinDiv = document.getElementById(elementid);
    if (isIE && typeof (__Win__IsFilterClose) != "undefined" && __Win__IsFilterClose) {
        __Win__BlockFlag = false;
        HideIEWinErrMsgTips(objWinDiv.id);
    }
    else {
        objWinDiv.style.visibility = "hidden";
    }
}

function HideDiv(elementid) {
    var obj___ = document.getElementById(elementid + "____")
    if (obj___ == null || typeof (obj___) == "undefined") {
        return;
    }
    var opacty = obj___.filters.alpha.opacity;
    obj___.filters.alpha.opacity = 100;
    document.getElementById(elementid).style.visibility = "hidden";
}

function HideIEWinErrMsgTips(elementid) {
    var obj___ = document.getElementById(elementid + "____")
    if (obj___ == null || typeof (obj___) == "undefined") {
        return;
    }
    var opacty = obj___.filters.alpha.opacity;
    document.getElementById(elementid).style.visibility = "hidden";
}


function ValidatorUpdateDisplay(val, val2, msg) {
    var closestr = "<div id=\"tipdown\" style=\"position:absolute;z-index:9999;\" class=\"tip-down\"></div><span style=\"cursor:pointer;color:red\" title=\"关闭提示\" onclick=\"HideWinErrMsgTips('" + val.id + "')\">关闭</span>";
    val.innerHTML = "<div style=\"position:absolute;z-index:9999;filter:alpha(opacity=100)\" class='tip-bg' id='" + val.id + "____'><div class=\"tip-bulb\">" + msg + closestr + "</div></div>";
    obj = document.getElementById(val.id);
    var obj2 = document.getElementById(val.id + "____");
    var WinElementPos = getWinElementPos(val2)
    if (WinElementPos == false) {
        //debugger;
    }
    else {
        //提示中向下的小角
        var objtipdown = document.getElementById("tipdown");
        if (val2.offsetParent.cellIndex > 2 && obj2.offsetWidth > val2.offsetParent.offsetWidth) {
            obj2.style.left = (parseInt(isIE ? val2.parentTextEdit.offsetWidth : val2.ownerDocument.width) - parseInt(obj2.offsetWidth)).toString() + "px";
            //控制提示中向下的小角
            objtipdown.style.left = (parseInt(WinElementPos.x) - (parseInt(isIE ? val2.parentTextEdit.offsetWidth : val2.ownerDocument.width) - parseInt(obj2.offsetWidth))).toString() + "px";
            objtipdown.style.top = "0px";
        }
        else {
            objtipdown.style.top = "0px";
            objtipdown.style.left = "0px";
            obj2.style.left = (parseInt(WinElementPos.x)).toString() + "px";
        }
        if (val2.tagName.toLowerCase() == "textarea") {
            obj2.style.top = (parseInt(WinElementPos.y) - 20 - 6).toString() + "px";
        }
        else if (val2.tagName.toLowerCase() == "select" && val2.size > 0) {
            obj2.style.top = (parseInt(WinElementPos.y) - 20 - 6).toString() + "px";
        }
        else {
            obj2.style.top = (parseInt(WinElementPos.y) - parseInt(WinElementPos.h) - 6).toString() + "px";
        }
    }
    val.style.visibility = val.isvalid ? "hidden" : "visible";
    __Win__BlockFlag = true;
    //if (typeof (__Win__IsAutoClose) != "undefined" && __Win__IsAutoClose && typeof (__Win__CloseWaitTime) != "undefined")
    //    setTimeout("HideWinErrMsgTips('" + val.id + "')", __Win__CloseWaitTime);
}

//得到某obj的x,y坐标,兼容大部分的浏览器
function getWinElementPos(obj) {
    var ua = navigator.userAgent.toLowerCase();
    var isOpera = (ua.indexOf('opera') != -1);
    var isIE = (ua.indexOf('msie') != -1 && !isOpera); // not opera spoof
    var el = obj;
    if (el.parentNode === null || el.style.display == 'none') {
        return false;
    }
    var parent = null;
    var pos = [];
    var box;
    if (el.getBoundingClientRect) //IE
    {
        box = el.getBoundingClientRect();
        var scrollTop = Math.max(document.documentElement.scrollTop, document.body.scrollTop);
        var scrollLeft = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft);
        return { x: box.left + scrollLeft, y: box.top + scrollTop, h: box.bottom - box.top };
    }
    else if (document.getBoxObjectFor) // gecko
    {
        box = document.getBoxObjectFor(el);
        var borderLeft = (el.style.borderLeftWidth) ? parseInt(el.style.borderLeftWidth) : 0;
        var borderTop = (el.style.borderTopWidth) ? parseInt(el.style.borderTopWidth) : 0;
        pos = [box.x - borderLeft, box.y - borderTop];
    }
    else // safari & opera
    {
        pos = [el.offsetLeft, el.offsetTop];
        parent = el.offsetParent;
        if (parent != el) {
            while (parent) {
                pos[0] += parent.offsetLeft;
                pos[1] += parent.offsetTop;
                parent = parent.offsetParent;
            }
        }
        if (ua.indexOf('opera') != -1 || (ua.indexOf('safari') != -1 && el.style.position == 'absolute')) {
            pos[0] -= document.body.offsetLeft;
            pos[1] -= document.body.offsetTop;
        }
    }

    if (el.parentNode) {
        parent = el.parentNode;
    }
    else {
        parent = null;
    }

    while (parent && parent.tagName != 'BODY' && parent.tagName != 'HTML') { // account for any scrolled ancestors
        pos[0] -= parent.scrollLeft;
        pos[1] -= parent.scrollTop;

        if (parent.parentNode) {
            parent = parent.parentNode;
        }
        else {
            parent = null;
        }
    }
    return { x: pos[0], y: pos[1] };
}
//////////////////////////////////////////////////////////////////////////Function
// JScript 文件
//显示虚线边框
function ShowElementBorder(ctrlId) {

    var ctrl = document.getElementById(ctrlId);
    //ctrl.parentNode.className = isIE ? "span_dashed" : "span_dashed_ff";
    if (isIE)
        setStyle("span_dashed", ctrl.parentNode)
    else
        setStyle("span_dashed_ff", ctrl.parentNode);
    //objWinDiv.style.visibility = "hidden";
}

//隐藏虚线边框
function HideElementBorder(ctrlId) {
    var ctrl = document.getElementById(ctrlId);
    if (isIE)
        setStyle("span_solid", ctrl.parentNode)
    else
        setStyle("span_solid_ff", ctrl.parentNode);
}

function setStyle(className, ctrl) {
    switch (className) {
        case "span_dashed":
            ctrl.style.border = "dashed 1px red";
            break;
        case "span_solid":
            ctrl.style.border = "solid 0px #999";
            break;
        case "span_dashed_ff":
            ctrl.style.outline = "red dashed 1px";
            break;
        case "span_solid_ff":
            ctrl.style.outline = "#999 solid 0px";
            break;
    }
}

//显示红色边框
function AddBorder(ctrlId) {
    var ctrl = document.getElementById(ctrlId);
    BorderSpan = document.createElement('span');
    BorderSpan.id = 'span_' + ctrl.id;
    setStyle('span_solid', BorderSpan);
    ParentSpanNumber = ctrl.parentNode.getElementsByTagName("span").length;
    var obj = document.getElementById('span_' + ctrl.id);
    //防止当不停地点击保存按钮时会出现很多span，
    //if (ParentSpanNumber == 1)
    if (obj == null || typeof (obj) == "undefined") {
        ctrl.parentNode.insertBefore(BorderSpan, ctrl); //关键所在
        //ie6,ie7bug -checkbox radio appendchild后状态丢失
        //暂时如下解决 change by jt 2010-5-19
        if (ctrl.type == "checkbox" || ctrl.type == "radio") {
            var checkstatus = ctrl.checked;
            BorderSpan.appendChild(ctrl).checked = checkstatus;
        } else {
            BorderSpan.appendChild(ctrl);
        }
    }
    //val.style.visibility = val.isvalid ? "hidden" : "visible";//问号表达式,若isvalid为真时,visibility=hidden,否则为visible,isvalid是控件的属性
}

//验证varchar的输入长度
//ctrl  待验证的控件
function VarcharValidLength(ctrl) {
    var length = 0;
    //验证普通文本
    if (ctrl.attributes[MaxLength] != null) {
        length = ctrl.attributes[MaxLength].value;
    }
    //验证多行文本（多行文本会隐藏MaxLength属性）
    else if (ctrl.attributes["textlength"] != null) {
        length = ctrl.attributes["textlength"].value;
    }
    else if (ctrl.attributes["TextLength"] != null) {
        length = ctrl.attributes["TextLength"].value;
    }
    else {
        return true;
    }
    var objstr = ctrl.value;
    //输入内容的长度
    var objlength = ctrl.value.length;
    while (objstr.length > 0) {
        //判断中文所在位置
        var i = escape(objstr).indexOf('%u');
        if (i != -1) {
            //截取中文之后的内容
            objstr = objstr.substring(i + 1);
            //增加长度
            objlength++;
        }
        else {
            break;
        }
    }
    if (objlength > length) {
        return false;
    }
    return true;
}

//验证nvarchar的输入长度
//ctrl  待验证的控件
function NvarcharValidLength(ctrl) {
    var length = 0;
    if (ctrl.attributes[MaxLength] != null) {
        length = ctrl.attributes[MaxLength].value;
    }
    else if (ctrl.attributes["textlength"] != null) {
        length = ctrl.attributes["textlength"].value;
    }
    else {
        return true;
    }
    var objlength = ctrl.value.length;
    if (objlength > length) {
        return false;
    }
    return true;
}

//验证Decimal的输入长度
//ctrl  待验证的控件
function isDecimal(ctrl) {
    //判断是否为数值
    if (!isNaN(StrTrim(ctrl.value))) {
        var number = StrTrim(ctrl.value);
        var precision = "";
        if (ctrl.attributes["precision"] != null) {
            //获取设置的精度控制
            precision = ctrl.attributes["precision"].value;
        }
        //拆分整数位和小数位
        var pre = precision.split(",");
        var num = number.split(".");

        if (num[1])//存在小数位的情况
        {
            //小数位是否超出有效位数（不包括有效位数之后为0的）
            if (num[1].length > parseInt(pre[1], 10) && parseInt(num[1].substr(pre[1]), 10) != 0) {
                return false;
            }
            //整数位是否超出
            else if (String(parseInt(num[0]), 10).length > parseInt(pre[0], 10) - parseInt(pre[1], 10)) {
                return false;
            }
        }
        else if (num[0].length > parseInt(pre[0], 10) - parseInt(pre[1], 10))//不存在小数位直接判断有效位数是否超出
        {
            return false;
        }
        return true;
    }
    else {
        return false;
    }
}


//验证输入数值的长度
//ctrl  待验证的控件
//type  验证的类型
function valNumber(v, type) {
    var flag = false;
    switch (type) {
        case "int":
            if (parseInt(v, 10) >= -2147483648 && parseInt(v, 10) <= 2147483647)
                flag = true;
            break;
        case "smallint":
            if (parseInt(v, 10) >= -32768 && parseInt(v, 10) <= 32767)
                flag = true;
            break;
        case "tinyint":
            if (parseInt(v, 10) >= 0 && parseInt(v, 10) <= 255)
                flag = true;
            break;
        case "bigint":
            if (parseInt(v, 10) >= -9223372036854775808 && parseInt(v, 10) <= 9223372036854775807)
                flag = true;
            break;
    }
    return flag;
}

/*
======================================================================================
验证自定义表达式
======================================================================================
*/
function CheckRegex(ctrl) {

    var regex = ""; //自定义正则字符串
    if (ctrl.attributes["regex"] != null) {
        regex = ctrl.attributes["regex"].value;
    }
    else {
        return true;
    }
    var regexExpression = regex.split(RegexMark)[0]; //正则表达式
    var testRe = "";
    //debugger;
    switch (regexExpression) {
        case "mail":
            testRe = "^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$";
            break;
        case "shortdate":
            testRe = "^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$";
            break;
        case "int":
            testRe = "^[0-9]*[1-9][0-9]*$";
            break;
        default:
            testRe = regexExpression;
            break;
    }
    var re = new RegExp(testRe);
    if (re.test(ctrl.value)) {
        return true;
    }
    else {
        return false;
    }
}

//显示控件的边框和提示
function show(ctrl, _function, value) {
    var ctrlid = ctrl.id;
    var Msg = "";
    var tip = value;
    ctrl.onfocus = "ctrlonfocus(ctrl);"
    ctrl.onblue = "ctrlonblur(ctrl);"
    if (value == null || value == "") {
        tip = "不能为空！";
    }
    if (ctrl.attributes["msg"] != null)//该文本代表的信息，这些属性是公司框架自定义的
    {
        Msg = ctrl.attributes["msg"].value;
    }
    else if (ctrl.attributes["Msg"] != null)//该文本代表的信息，这些属性是公司框架自定义的
    {
        Msg = ctrl.attributes["Msg"].value;
    }
    CreateDiv();
    AddBorder(ctrlid);
    ShowElementBorder(ctrlid);
    if (isShowCustomTip == true) {
        if (document.getElementById("ErrorDiv").style.visibility != "visible") {
            ValidatorUpdateDisplay(document.getElementById("ErrorDiv"), ctrl, Msg + tip);
        }
    }

    //增加控件事件
    ctrl.onfocus = function () {
        isShowCustomTip = true;
        HideWinErrMsgTips("ErrorDiv");
        _function();
    }
    ctrl.onblur = function () {
        isShowCustomTip = true;
        HideWinErrMsgTips("ErrorDiv");
        _function();
    }

    //处理checkboxlist

    if (ctrlid.toLowerCase().indexOf("checkboxlist") != -1) {
        var objctrl = isIE ? ctrl : ctrl.rows[0];
        for (var i = 0; i < objctrl.cells.length; i++) {
            for (var j = 0; j < objctrl.cells[i].children.length; j++) {
                if (j % 2 == 0) {
                    objctrl.cells[i].children[j].onclick = function () {
                        var obj1 = ctrl;
                        var inputs = obj1.getElementsByTagName("input");
                        var ischeck = false;
                        for (var i = 0; i < inputs.length; i++) {
                            if (inputs[i].checked) {
                                ischeck = true;
                                break;
                            }
                        }
                        isShowCustomTip = !ischeck;
                        HideWinErrMsgTips("ErrorDiv");
                        _function();
                    }
                    objctrl.cells[i].children[j].onfocus = objctrl.cells[i].children[j].onclick;
                }
                else {
                    objctrl.cells[i].children[j].onclick = function () {
                        var obj1 = ctrl;
                        var inputs = obj1.getElementsByTagName("input");
                        var ischeck = false;
                        for (var i = 0; i < inputs.length; i++) {
                            if (inputs[i].checked) {
                                ischeck = true;
                                break;
                            }
                        }
                        isShowCustomTip = !ischeck;
                        HideWinErrMsgTips("ErrorDiv");
                        _function();
                    }
                    objctrl.cells[i].children[j].onblur = objctrl.cells[i].children[j].onclick;
                }
            }
        }
    }
}

//隐藏控件的提示
function hidden(ctrl) {
    var ctrlid = ctrl.id;
    //    HideWinErrMsgTips("ErrorDiv");
    HideElementBorder(ctrlid);
}
